/*
 * main.c
 *
 *  Created on: Mar 8, 2011
 *      Author: zhanglei
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "tuntap.h"

char icmp[] = { 0x45, 0x00, 0x00, 0x54, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01,
		0xd2, 0x0a, 0x79, 0x30, 0x9e, 0xb5, 0x77, 0x4b, 0xd9, 0x6d, 0x08, 0x00,
		0x73, 0x42, 0xf3, 0x10, 0x00, 0x01, 0x08, 0x46, 0x76, 0x4d, 0x22, 0x15,
		0x06, 0x00, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
		0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
		0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
		0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
		0x36, 0x37 };

int main(int argc, char **argv) {
	int tunfd = -1;
	char dev[128] = "tun";

	if ((tunfd = tun_open(dev)) < 0) {
		fprintf(stderr, "create tun file descriptor failed!\n");
		exit(-1);
	}

	if (tun_set_ip(dev, inet_addr("192.168.1.1")) < 0) {
		fprintf(stderr, "set ip address failed!\n");
		exit(-1);
	}

	if (tun_set_netmask(dev, inet_addr("255.255.255.128")) < 0) {
		fprintf(stderr, "set netmask failed!\n");
		exit(-1);
	}

	if (tun_activate(dev) < 0) {
		fprintf(stderr, "activate tun failed\n");
	}

	int i = 2;
	char srcip[] = "255.255.255.255";
	char recvbuf[1500];
	for (; i < 10; ++i) {
		sprintf(srcip, "192.168.1.%d", i);
		printf("ping from %s (press enter to proceed)\n", srcip);
		getchar();
		set_ipaddr(icmp, sizeof(icmp), inet_addr(srcip), 0);
		write(tunfd, icmp, sizeof(icmp));
		read(tunfd, recvbuf, 1500);
		decode_packet(recvbuf);
	}

	return EXIT_SUCCESS;
}
